<template>
	<view class="page">
		<!-- <view class="hidden">这是一个test</view> -->
		<swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" class="carousel" v-show="swipperFlag">
			<swiper-item v-for="pic in carouselList" :key="pic">
				<image :src="pic" class="carousel"></image>
			</swiper-item>
		</swiper>

		<!-- 菜单主体 -->
		<view class="menu-body">
			<!-- 左侧列表 菜品分类 -->
			<scroll-view class="menu-left" scroll-y="true">
				<block v-for="foodCategory in foodCategoryList" :key='foodCategory.categoryId'>
					<view :class="[categoryClass,curNav==foodCategory.categoryId?activeClass:'']" :data-categoryId="foodCategory.categoryId"
					 @click="changeRightMenu">
						{{foodCategory.categoryName}}
					</view>
				</block>
			</scroll-view>
			<!-- 右侧列表 分类菜品列表 -->
			<scroll-view :class="[menuActive?menuActiveClass:menuRightClass]" scroll-y="true" upper-threshold="10"
			 lower-threshold="0" @scrolltoupper="showSwipper" @scrolltolower="closeSwipper">
				<block v-for="food in chooseFoodList" :key="food.foodId">
					<view class="single-food-wrap">
						<!-- 图片 -->
						<view class="img-box">
							<image class="img-box" :src='baseUrl+food.foodImage'></image>
						</view>
						<!-- 菜品其他信息 -->
						<view class="desc-box">
							<!-- 菜名 -->
							<view class="food-name">{{food.foodName}}</view>
							<!-- 购买按钮 -->
							<view class="price-operator-wrap">
								<!-- 价格 -->
								<view class="food-price">{{food.foodPrice.toFixed(1)}}</view>
								<view class="operator-wrap">
									<!-- 减号 -->
									<view class="iconfont icon-minus icon-font" :hidden="food.sellCount<=0" :data-id="food.foodId" @click="minusCount"></view>
									<!-- 数量 -->
									<view class="sale-num" :hidden="food.sellCount<=0" :data-id="food.foodId">{{food.sellCount}}</view>
									<!-- 加号 -->
									<view class="iconfont icon-add icon-font" :data-id="food.foodId" @click="addCount"></view>
								</view>

							</view>
						</view>
					</view>
				</block>
			</scroll-view>
		</view>
		<!-- 小计提示 -->
		<view class="bottom_box">
			<view class="shopCart_box" @click="cascadeToggle">
				<image class="shopCart_img" src="../../static/shopCart.png"></image>
			</view>
			<view class="all_money">总计：{{totalPrice}} 元，共 {{totalNum}} 件</view>
			<button class="choose_ok" open-type="getUserInfo" lang="zh_CN" @getuserinfo="confirm">选好了</button>
		</view>


		<!-- 购物车弹窗 -->
		<!-- 遮罩层 -->
		<view :hidden="maskFlag" class="modal-mask" @tap="cascadeToggle"></view>
		<view class="cart_popup" :animation="animationData">
			<!-- 标题 -->
			<view class="shopCart_title">
				<text class="shopCart_close" @click="cascadeToggle">返回</text>
				购物车 ￥{{totalPrice}}
				<text class="shopCart-clear" @click="cleanCart">清空购物车</text>
			</view>
			<!-- 购物车列表 -->
			<scroll-view scroll-y="true" style="height: 270px;">
				<block v-for="(item,index) in cartList" :key="item.foodId">
					<view class="cart_cell">
						<!-- 菜品名称及价格 -->
						<view>
							<text class="cell_name">{{item.foodName}}</text>
							<text class="cell_price">{{item.foodPrice.toFixed(1)}}</text>
						</view>
						<!-- 操作 -->
						<view class="operator-wrap">
							<!-- 减号 -->
							<view class="iconfont icon-minus icon-font" @click="minusCount" :data-id="item.foodId"></view>
							<!-- 数量 -->
							<view class="sale-num">{{item.sellCount}}</view>
							<!-- 加号 -->
							<view class="iconfont icon-add icon-font" @click="addCount" :data-id="item.foodId"></view>
							<!-- 删除 -->
							<!-- <icon class="cell_clear" type="clear" size="20"></icon> -->
							<view class="iconfont icon-clear cell_clear" @click="deleteCartOne" :data-id="item.foodId" :data-index="index"></view>
						</view>

					</view>
				</block>
			</scroll-view>
		</view>

	</view>
</template>

<script>
	import common from "../../common/common.js"
	export default {
		data() {
			return {
				// 变量
				baseUrl: 'http://localhost:8080/sell/',
				isHidden: false,
				menuActive: false,
				curNav: 0,
				maskFlag: true,
				totalPrice: 0,
				totalNum: 0,
				maskVisible: 'hidden',
				animationData: {},
				animationMaskData: {},

				// 样式
				swipperFlag: true,
				menuRightClass: 'menu-right',
				menuActiveClass: 'menu-right-active',
				categoryClass: 'category',
				hiddenClass: 'hidden',
				showClass: 'show',
				activeClass: 'active',

				// 列表
				carouselList: [],
				foodCategoryList: [],
				foodList: [],
				cartList: [],
				chooseFoodList: []

			}
		},
		onLoad() {
			// var serverUrl = common.serverUrl;
			var serverUrl = this.serverUrl;
			uni.showLoading({
				title: '正在加载……',
				mask: false
			});
			// 请求轮播图数据
			uni.request({
				url: serverUrl + '/slideShow',
				method: 'GET',
				data: {},
				success: res => {
					// console.log(res.data)
					if (res.data.code == 200) {
						this.carouselList = res.data.data
					}
				},
				fail: () => {},
				complete: () => {}
			});
			// 请求菜品分类数据
			uni.request({
				url: serverUrl + '/getAllFoodCookCategory',
				method: 'GET',
				data: {},
				success: res => {
					// console.log(res.data)
					this.foodCategoryList = res.data
					// console.log(this.foodCategoryList[0].categoryId)
					this.curNav = this.foodCategoryList[0].categoryId
				},
				fail: () => {},
				complete: () => {}
			});
			// 请求菜品信息数据
			uni.request({
				url: serverUrl + '/wGetAllFood',
				method: 'GET',
				data: {},
				success: res => {
					// console.log(res.data.data)
					this.foodList = res.data.data
					// console.log(this.foodList)
					// this.curNav=this.foodList[0].categoryId
					// 按照类别更新菜单列表
					this.updateFoodList(this.curNav)
					// 初始化购买数量
					for (var i in this.foodList) {
						this.foodList[i].sellCount = 0
					}
					// 获取购物车缓存数据
					var cartList = uni.getStorageSync('cart') || [];
					// 购物车购物总数量和总价
					var totalPrice = this.totalPrice
					var totalNum = this.totalNum
					// 判断购物车是否有数据，有数据则将菜单与购物车相关联
					if (cartList.length > 0) {
						for (var i in cartList) {
							for (var j in this.chooseFoodList) {
								if (cartList[i].foodId == this.chooseFoodList[j].foodId) {
									this.chooseFoodList[j].sellCount = cartList[i].sellCount;
								}
							}
							totalPrice += cartList[i].foodPrice * cartList[i].sellCount;
							totalNum += Number(cartList[i].sellCount);
						}
					}
					// 赋值
					this.cartList = cartList;
					this.totalPrice = totalPrice.toFixed(2)
					this.totalNum = totalNum
				},
				fail: () => {
					uni.showModal({
						title: '网络连接失败',
						content: '服务器无法访问……',
						showCancel: false,
						cancelText: '',
						confirmText: '知道了',
						success: res => {
							if (res.confirm) {
								console.log('用户点击了确定')
							}
						},
						fail: () => {},
						complete: () => {}
					});
				},
				complete: () => {
					uni.hideLoading()
				}
			});

		},
		onShow() {
			var animation = uni.createAnimation({
				duration: 200,
				timingFunction: 'ease-in-out',
				delay: 0
			});
			this.animation = animation;

			var animationMask = uni.createAnimation({
				duration: 200,
				timingFunction: 'linear',
			});
			this.animationMask = animationMask;
		},

		methods: {
			// 关闭轮播图
			closeSwipper(e) {
				// console.log(e)
				this.swipperFlag = false;
				this.menuActive = true;
			},
			// 显示轮播图
			showSwipper(e) {
				this.swipperFlag = true;
				this.menuActive = false;
			},

			// 根据选中的分类切换不同的foodlist内容
			updateFoodList(categoryId) {
				// console.log(this.foodList)
				var allFoodList = this.foodList;
				var tmpFoodList = [];
				for (var i in allFoodList) {
					// console.log(allFoodList[i])
					if (allFoodList[i].fccId == categoryId) {
						tmpFoodList.push(allFoodList[i])
					}
				}
				// console.log(tmpFoodList)
				this.chooseFoodList = tmpFoodList;
				this.curNav = categoryId
			},
			// 切换分类
			changeRightMenu(e) {
				// console.log(e.currentTarget.dataset.categoryId)
				// console.log(e)
				var categoryId = e.currentTarget.dataset.categoryid;
				// console.log(categoryId)
				this.updateFoodList(categoryId)
			},
			// 根据value删除cartList中的元素
			removeByValue(list, val) {
				for (var i in list) {
					if (list[i].foodId == val) {
						list.splice(i, 1);
						break;
					}
				}
			},
			// 减少数量
			minusCount(e) {
				// 获取菜品id
				// console.log(e.currentTarget.dataset)
				var foodId = e.currentTarget.dataset.id
				var chooseFoodList = this.chooseFoodList;
				// 获取购物车列表数据
				var cartList = uni.getStorageSync('cart') || []

				for (var i in chooseFoodList) {
					if (chooseFoodList[i].foodId == foodId) {
						chooseFoodList[i].sellCount -= 1;
						if (chooseFoodList[i].sellCount <= 0) {
							chooseFoodList[i].sellCount = 0;
						}
						// 更新购物车数据
						if (cartList.length > 0) {
							for (var j in cartList) {
								if (cartList[j].foodId == foodId) {
									cartList[j].sellCount -= 1;
									if (cartList[j].sellCount <= 0) {
										// 删除
										this.removeByValue(cartList, foodId)
									}
									if (cartList.length <= 0) {
										this.chooseFoodList = chooseFoodList;
										this.cartList = []
										this.totalNum = 0;
										this.totalPrice = 0;
										this.cascadeClose()
									}
									try {
										uni.setStorageSync('cart', cartList)
									} catch (e) {
										//TODO handle the exception
										console.log(e)
									}
								}
							}
						}
					}
				}
				// 更新数据，重新计算金额
				this.cartList = cartList;
				this.chooseFoodList = chooseFoodList;
				// this.getTotalPrice()
				var total = common.getTotalPrice(cartList)
				this.totalNum = total[0];
				this.totalPrice = total[1];

			},
			// 增加数量
			addCount(e) {
				var me = this
				// 获取菜品id
				// console.log(e.currentTarget.dataset)
				var foodId = e.currentTarget.dataset.id
				// console.log(foodId)
				var chooseFoodList = me.chooseFoodList;
				// 获取购物车列表数据
				var cartList = uni.getStorageSync('cart') || [];

				// 标志--购物车中是否已有所选菜品
				var hasFlag = false;
				// 找到所选菜品，购买数量加1
				for (var i in chooseFoodList) {
					// console.log(chooseFoodList[i].foodId)
					if (chooseFoodList[i].foodId == foodId) {
						// console.log('before', chooseFoodList[i].sellCount)
						chooseFoodList[i].sellCount += 1;
						// console.log('after',chooseFoodList[i].sellCount)
						// 更新购物车信息
						if (cartList.length > 0) {
							for (var j in cartList) {
								if (cartList[j].foodId == foodId) {
									cartList[j].sellCount += 1;
									hasFlag = true;
									try {
										// 购物车信息放入缓存
										uni.setStorageSync('cart', cartList)
									} catch (e) {
										//TODO handle the exception
										console.log(e)
									}
									break;
								}
							}
							// 若购物车中没有此菜品，添加一个
							if (!hasFlag) {
								cartList.push(chooseFoodList[i])
							}
						} else {
							cartList.push(chooseFoodList[i])
						}
						try {
							uni.setStorageSync('cart', cartList)
						} catch (e) {
							//TODO handle the exception
							console.log(e)
						}
						break;
					}

				}
				// 更新数据
				me.cartList = cartList
				// console.log(chooseFoodList)
				me.chooseFoodList = chooseFoodList
				// console.log(me.chooseFoodList)
				// 重新计算金额
				// me.getTotalPrice()
				var total = common.getTotalPrice(cartList)
				this.totalNum = total[0];
				this.totalPrice = total[1];
			},
			// 购物车弹窗
			// 显示购物车
			cascadeOpen() {
				// 打开动画
				this.animation.translate(0, -300).step();
				this.animationData = this.animation.export();

				// 遮罩渐变动画

				this.animationMask.opacity(0.8).step();
				this.animationMaskData = this.animationMask.export();

				this.maskVisible = 'show';
				this.maskFlag = false;
			},
			// 关闭购物车
			cascadeClose() {
				// 关闭购物车动画
				this.animation.translate(0, 300).step();
				this.animationData = this.animation.export();
				// 遮罩渐变动画
				this.animationMask.opacity(0).step();
				this.animationMaskData = this.animationMask.export();
				// 隐藏遮罩层
				this.maskVisible = 'hidden';
				this.maskFlag = true;
			},
			// 切换购物车开关
			cascadeToggle(e) {
				var cartList = this.cartList;
				// console.log(cartList.length)
				// console.log(this.maskVisible)
				if (cartList.length > 0) {
					if (this.maskVisible == 'hidden') {
						// 显示购物车
						this.cascadeOpen()
					} else {
						// 关闭购物车
						this.cascadeClose()
					}
				} else {
					// 关闭购物车
					this.cascadeClose()
				}
			},
			// 清空购物车
			cleanCart(e) {
				for (var i in this.foodList) {
					this.foodList[i].sellCount = 0;
				}
				try {
					uni.setStorageSync('cart', '')
				} catch (e) {
					//TODO handle the exception
					console.log(e)
				}
				this.cartList = []
				this.totalNum = 0
				this.totalPrice = 0
				// 关闭购物车
				this.cascadeClose()
			},
			// 删除购物车单个商品
			deleteCartOne(e) {
				var foodId = e.currentTarget.dataset.id;
				var index = e.currentTarget.dataset.index;
				// console.log('index',index)
				var cartList = uni.getStorageSync('cart')
				for (var i in this.foodList) {
					if (this.foodList[i].foodId == foodId) {
						this.foodList[i].sellCount = 0;
					}
				}
				// 删除index位置的值
				cartList.splice(index, 1);
				if (cartList.length <= 0) {
					this.cartList = [];
					this.totalNum = 0;
					this.totalPrice = 0;
					// 关闭购物车
					this.cascadeClose()
				}
				// 更新缓存中的购物车信息
				try {
					uni.setStorageSync('cart', cartList)
				} catch (e) {
					//TODO handle the exception
					console.log(e)
				}
				this.cartList = cartList
				// 更新价格
				// this.getTotalPrice()
				var total = common.getTotalPrice(cartList)
				this.totalNum = total[0];
				this.totalPrice = total[1];
			},
			// 去确认
			confirm(e) {
				var me = this
				// 先验证是否授权
				wx.getSetting({
					success(res) {
						// console.log(res)
						if (!res.authSetting['scope.userInfo']) {
							uni.showToast({
								title: '需要授权才可使用哦',
								icon: 'none'
							});
						} else {
							// 下单操作
							if (me.totalNum > 0 && me.totalPrice > 0) {
								uni.showLoading({
									title: '请稍等...',
									mask: false
								});
								// 获取用户信息
								var userInfo = e.detail.userInfo;
								var wxUserInfo = uni.getStorageSync('wxUserInfo');
								// console.log(wxUserInfo)

								wxUserInfo.userNickName = userInfo.nickName
								wxUserInfo.userCity = userInfo.city
								wxUserInfo.userGender = userInfo.gender

								uni.setStorageSync('wxUserInfo', wxUserInfo)
								// console.log(wxUserInfo)					
								// 跳转页面
								uni.navigateTo({
									url: '../confirm/confirm?num=' + me.totalNum + '&price=' + me.totalPrice,
									success: res => {},
									fail: () => {},
									complete: () => {}
								});
								uni.hideLoading()
							} else {
								uni.showToast({
									title: '您还未选择菜品~',
									image:'../../static/fail-white.png'
								});
							}
						}
					}
				})
			},

		}
	}
</script>

<style>
	@import url("index.css");
</style>
